package tech.yunland.shop.domain.dao;

import com.moyuer.bsf.domain.dao.BaseDao;
import org.hibernate.criterion.DetachedCriteria;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import tech.yunland.shop.domain.model.*;

import java.math.BigDecimal;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author: 袁首京<yuanshoujing@gmail.com> 16/4/14
 */
@Repository
public class SaleBillDao extends BaseDao<SaleBill, String> {


    @Autowired
    private StoreBillEntryDao storeBillEntryDao;
    @Autowired
    private StoreBillDao storeBillDao;
    @Autowired
    private GoodsDao goodsDao;
    @Autowired
    private SNGenerator generator;

    /**
     * 标记删除无用销售单头
     */
    public void deleteRepeat() {
        DetachedCriteria criteria = DetachedCriteria.forClass(SaleBill.class);
        List<SaleBill> repeat = this.findByCriteria(criteria);
        for (int i = 0; i < repeat.size(); i++) {
            SaleBill saleBill = repeat.get(i);
            if (saleBill.getEntries().size() == 0 || saleBill.getEntries() == null) {
                if (saleBill.getState() != -1) {
                    saleBill.setState(-1);
                }
                this.update(saleBill);
            }
        }

    }

    /**
     * 由销售单-->出库单
     *
     * @param bill
     * @return
     */
    public StoreBill saveStore(SaleBill bill) {

        StoreBill storeBill = new StoreBill();
        storeBill.setSn(generator.gen("sale", bill.getOrganId()));
        //形成出库单
        storeBill.setBizdate(bill.getBizdate());
        storeBill.setOrgan(bill.getOrgan());
        storeBill.setBizBillId(bill.getId());
        storeBill.setBizBillSn(bill.getSn());
        storeBill.setState(2);//状态设为2
        storeBill.setDirection(-1);//-1出库
        storeBill.setBiz_type(-2);//业务类型，-1 普通出库 -2 销售出库
        storeBill.setCreator(bill.getCreator());
        storeBill.setRemark(bill.getRemark() == null ? "" : bill.getRemark());

        Set<StoreBillEntry> entries = new HashSet<>();
        Set<SaleBillEntry> saleBillEntries = bill.getEntries();
        for (SaleBillEntry entry : saleBillEntries) {

            //构建出库单分录
            BigDecimal quantity = entry.getQuantity();
            Goods goods = entry.getGoods();

            Goods _goods = goodsDao.get(goods.getId());
            if (_goods.getKindCode().intValue() != 10) {
                continue;
            }

            StoreBillEntry storeBillEntry = new StoreBillEntry();
            storeBillEntry.setGoods(goods);
            storeBillEntry.setQuantity(quantity);
            storeBillEntry.setState(1);
            storeBillEntry.setOwner(storeBill);
            entries.add(storeBillEntry);
        }

        storeBill.setSaleBill(bill);
        storeBill.setEntries(entries);
        return storeBill;
    }

}
